package com.wayz.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 
 * <p>文件md5 支持超大文件</p>
 * 
 * @date 2016年6月14日
 * @author mahao
 */
public class FileMD5Helper {

	private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
			'f' };

	private static MessageDigest messagedigest = null;

	static {
		try {
			messagedigest = MessageDigest.getInstance("MD5");
		}
		catch (NoSuchAlgorithmException nsaex) {
			nsaex.printStackTrace();
		}
	}

	/**
	 * 
	 * <p>获取md5</p>
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 * @date 2016年5月10日
	 */
	public static String getFileMD5String(File file) throws IOException {
		FileInputStream in = null;
		FileChannel ch = null;
		try {
			in = new FileInputStream(file);
			ch = in.getChannel();
			// final MappedByteBuffer byteBuffer =
			// ch.map(FileChannel.MapMode.READ_ONLY, 0,file.length());
			ByteArrayOutputStream out = new ByteArrayOutputStream((int) file.length());
			byte[] cache = new byte[1048576];
			for (int i = in.read(cache); i != -1; i = in.read(cache)) {
				out.write(cache, 0, i);
			}
			messagedigest.update(out.toByteArray());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (ch != null) {
				ch.close();
			}
			if (in != null) {
				in.close();
			}

		}
		return bufferToHex(messagedigest.digest());
	}

	/**
	 * 
	 * <p>md5字符串</p>
	 * 
	 * @param s
	 * @return
	 * @date 2016年6月14日
	 */
	public static String getMD5String(String s) {
		return getMD5String(s.getBytes());
	}

	/**
	 * 
	 * <p>md5字节</p>
	 * 
	 * @param bytes
	 * @return
	 * @date 2016年6月14日
	 */
	public static String getMD5String(byte[] bytes) {
		messagedigest.update(bytes);
		return bufferToHex(messagedigest.digest());
	}

	/**
	 * 
	 * <p>校验密码</p>
	 * 
	 * @param password
	 * @param md5PwdStr
	 * @return
	 * @date 2016年6月14日
	 */
	public static boolean checkPassword(String password, String md5PwdStr) {
		String s = getMD5String(password);
		return s.equals(md5PwdStr);
	}

	private static String bufferToHex(byte bytes[]) {
		return bufferToHex(bytes, 0, bytes.length);
	}

	private static String bufferToHex(byte bytes[], int m, int n) {
		StringBuffer stringbuffer = new StringBuffer(2 * n);
		int k = m + n;
		for (int l = m; l < k; l++) {
			appendHexPair(bytes[l], stringbuffer);
		}
		return stringbuffer.toString();
	}

	private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
		char c0 = hexDigits[(bt & 0xf0) >> 4];
		char c1 = hexDigits[bt & 0xf];
		stringbuffer.append(c0);
		stringbuffer.append(c1);
	}

}
